<<template>
<div class="vue-box">
  <div class="upload-wrapper" :class="{'upload-status-bg': showStatusWrapper}" :style="{backgroundImage: 'url(' + imgUrl + ')'}">
  <input v-if="!destroyInput" @change="onChange" class="input" type="file" accept="image/*" multiple=""/>
  <!-- <input v-if="!destroyInput" @change="onChange" class="input" type="file" accept="image/jpg,image/jpeg,image/png,image/gif"  capture="camera" multiple=""/> -->
    <!-- 安卓设备保留capture属性 -->
    <!-- <input v-if="!isIos && !destroyInput" @change="onChange" class="input" type="file" accept="image/jpg,image/jpeg,image/png,image/gif" capture="camera" multiple=""/> -->
    <!-- 上传状态 -->
    <div v-if="showStatusWrapper" class="upload-status-wrapper">
      <i class="fail" v-if="showStatusFail">！</i>
      <i v-else>{{procent}}%</i>
    </div>
  </div>
  <crop ref="cropWrapper" v-show="showCrop" @hide="showCrop=false" @finish="setUpload"></crop>
</div>
</template>

<script>
import Exif from 'exif-js'
import Crop from './crop'
import ImageUtil from './image'
import axios from 'axios'
const defaultImg = '../../../static/images/upload_photo_bg.png'
import { getToken } from '@/utils/auth'
export default {
  components: {
    Crop
  },
  props: {
    defaultUrl: {
      type: String,
      default: ''
    }
  },
  watch: {
    defaultUrl() {
      this.setImageUrl()
    }
  },
  mounted() {
    this.setImageUrl()
  },
  data() {
    return {
      destroyInput: false, // 是否销毁input元素, 解决在第二次和第一次选择的文件相同时不触发onchange事件的问题
      isIos: ImageUtil.isIos, // 是否为ios设备
      imgUrl: '', // 显示的图片地址
      filename: '', // 上传的文件名称
      Orientation: '', // 拍照时的图片方向
      showCrop: false, // 是否显示裁剪组件
      showStatusWrapper: false, // 上传状态布局
      showStatusFail: false, // 上传失败
      procent: 0 // 上传进度
    }
  },
  methods: {
    setImageUrl() {
      this.imgUrl = this.defaultUrl ? this.defaultUrl : defaultImg
    },
    onChange(e) {
      // 监测input传入file文件
      let files = e.target.files
      let file = e.target.files[0]
      if (files.length > 1) {
        console.log('最多只能上传1张图片，请重新选择')
        return false
      }
      if (['image/jpg', 'image/jpeg', 'image/png', 'image/gif'].indexOf(file.type) < 0) {
        console.log('请上传图片')
        return false
      }
      if (file.size > 4* 1024 * 1024) {
        this.$toast('不能上传超过4M')
        return false
      }
      let url = ImageUtil.getObjectURL(file)
      this.filename = file.name
      console.log('this.filename: ', this.filename);
      this.destroyInput = true
      setTimeout(() => {
        this.destroyInput = false
      }, 20)
      // 获取拍照时的信息，解决拍出来的照片旋转问题
      let t = this
      Exif.getData(file, function() {
        let Orientation = Exif.getTag(file, 'Orientation')
        t.Orientation = Orientation
        t.initCrop(url)
      })
    },
    initCrop(url) {
        console.log('url: ', url);
      // 初始化裁剪
      this.showCrop = true
      this.$refs.cropWrapper.initCrop(url, this.Orientation)
    },

    setUpload(base64) {
      // 设置上传
      let t = this
      t.showCrop = false
      t.imgUrl = base64
      t.procent = 0
      t.showStatusFail = false
      t.showStatusWrapper = true
      // 先获取 七牛云token (注:此接口是我自己写的一个服务,用于生成七牛云token)

          // 拿到token后执行上传
          t.upload(base64)
    },
 upload(base64) {
      // 再执行上传
      let t = this
      let imgFile = ImageUtil.base64Img2Blog(base64)
      imgFile.lastModifiedDate = new Date()
      let config = {
        headers: {'Content-Type': 'application/x-www-form-urlencoded','Authorization':getToken() || localStorage.getItem('token')},
      }
      let fd = new FormData()
      fd.append('file_path', imgFile,t.filename)
      fd.append('fileName', t.filename)
      this.$http.post('/login/reception/fileUpload', fd, config).then(res => {
        let ret = res.data
        console.log('上传结果',JSON.stringify(ret))
        if (ret.status === 100) {
          // 上传成功
          t.showStatusWrapper = false
          let ossHost = 'https://saic-public-2.oss-cn-shanghai.aliyuncs.com/'
          let imgUrl = `${ossHost}${ret.data.file_path}`
          console.log(`上传成功, 图片链接:${imgUrl}`)
          t.$emit('setImg', imgUrl)
        } else {
          // 上传失败
          t.showStatusFail = true
        }
      })
}
  }
}
</script>

<style lang="scss" scoped>
.upload-wrapper {
  position: absolute;
  width: 100%;
  height: 60px;
  background-size: cover;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  border: 0;
  overflow: hidden;
  // border-radius: 50%;
  // margin: 20px auto;
  .input {
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    width: 100px;
    height: 100px;
    opacity: 0;
    -webkit-tap-highlight-color: rgba(0,0,0,0);
  }
  &.upload-status-bg:before {
    // 文件上传状态 半透明背景
    content: " ";
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    // background-color: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
  }
  .upload-status-wrapper {
    // 文件上传状态 布局
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    color: #fff;
    .fail {
      // 上传失败
      text-align: center;
      width: 25px;
      height: 25px;
      line-height: 25px;
      border-radius: 50%;
      background: #F43530;
    }
  }
}
</style>
